
package com.example.app;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;
public class MyWebViewClient extends WebViewClient {
    private static final String TAG = "MyWebViewClient";
    private static final String ALLOWED_HOST = "192.168.0.1";
    private static final int ALLOWED_PORT = 5000;

    // 处理 Android 5.0+ 的 shouldOverrideUrlLoading
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        return shouldOverrideUrlLoading(view, request.getUrl().toString());
    }

    // 处理旧版 Android 的 shouldOverrideUrlLoading
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Log.d(TAG, "Loading URL: " + url);

        Uri uri = Uri.parse(url);
        String host = uri.getHost();
        int port = uri.getPort(); // 未指定端口时返回 -1

        // 1. 允许所有 file:// 本地资源
        if (url.startsWith("file:")) {
            Log.d(TAG, "Allowing file URL");
            return false;
        }

        // 2. 允许目标主机和端口（考虑端口未指定情况）
        if (ALLOWED_HOST.equals(host)) {
            // 端口匹配 或 未指定端口（使用默认HTTP端口80）
            if (port == ALLOWED_PORT || port == -1) {
                Log.d(TAG, "Allowed host and port, loading in WebView");
                return false; // WebView内部加载
            }
        }

        // 3. 其他链接用外部浏览器打开
        Log.d(TAG, "Redirecting to external browser: " + url);
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            view.getContext().startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "Failed to open external browser", e);
        }
        return true;
    }

    // 添加错误处理
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        Log.e(TAG, "WebView error (" + errorCode + "): " + description);
        Log.e(TAG, "Failing URL: " + failingUrl);

        // 显示错误信息（可选）
        view.loadData(
                "<h3>加载失败</h3><p>错误代码: " + errorCode + "</p><p>" + description + "</p>",
                "text/html",
                "UTF-8"
        );
    }
}